package com.shunli.cterminal.util;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.google.common.base.Throwables;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.function.Supplier;

/**
 * 业务型线程池
 *
 * @Author: 清水
 * @Date: 2025/4/9
 */
@Data
@Slf4j
public class AsyncUtils {

    private static ThreadFactory nameFactory = new ThreadFactoryBuilder()
            .setNamePrefix("examples-middle-pool-").build();

    private static ExecutorService service =
            //Runtime.getRuntime().availableProcessors()
            new ThreadPoolExecutor(
                    10,
                    10,
                    1, TimeUnit.MINUTES,
                    new LinkedBlockingQueue<>(200),
                    nameFactory,
                    new ThreadPoolExecutor.CallerRunsPolicy());


    public static <T> CompletableFuture<T> supplyAsync(Supplier<T> supplier) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                return supplier.get();
            } catch (Exception e) {
                log.error("examples-middle-supplyAsync[]有返回值异步任务执行失败 cause: {}", Throwables.getStackTraceAsString(e));
                return null;
            }
        }, service);
    }

    public static <T> void runAsync(Supplier<T> supplier) {
        CompletableFuture.runAsync(() -> {
            try {
                supplier.get();
            } catch (Exception e) {
                log.error("examples-middle-runAsync[]无返回值异步任务执行失败 cause: {}", Throwables.getStackTraceAsString(e));
            }
        }, service);
    }
}
